<?php
namespace app\index\controller;

use think\Controller;
use app\index\model\Member as Members;
use app\index\model\Putlog;
use app\index\model\Contract;
use app\index\model\Order;
use app\index\model\OrderContract;
use app\index\model\Notice;
use app\index\model\Card;
use app\index\model\Bankcode;
use app\index\model\Project;
use app\index\model\Lookinto;
use app\index\model\Invest;
use app\index\model\Question;
use app\index\model\Archive;
use expand\BestSignDemo;
use expand\Yunst;
use app\index\model\Mobilelog;

use think\Db;

class Member extends Common
{
	public $userId;
	public $cModel;
	public $check_action=['authentication','lookinto','assess','smrz','service','serviceType','getLookName','sendcode','sendcode1'];
    public function _initialize(){
        parent::_initialize();
		if(!CheckMemberLogin()){
			$this->redirect('Login/index');
		}

        if(!in_array(ACTION_NAME,$this->check_action)){
            if(session('isCheck')!=1){
                $this->redirect('member/authentication');
            }
        }

		$this->userId = session('UID');
		$this->cModel = new Members;
		$member = $this->cModel->where(['id'=>$this->userId])->find();
		if(empty($member['head_thumb'])){
			$member['head_thumb'] = '/static/global/face/default.png';
		}
		$this->assign('member',$member);
		$lookModel = new Lookinto();
		$isLookInto = $lookModel->where(['uid'=>$member['id']])->order('create_time desc')->limit(1)->value('create_time');
		if(empty($isLookInto)){
			$this->assign('wantToLookinto',1);
		}
		if($member['is_check'] == 1 && !$member['task_id']){
			$credential= ['identity'=>$member['certificate']];
			$this->ToBsetSign($member['username'],$member['mobile'],$credential);
		}
		if($member['is_check'] == 1 && !$member['bizUserId']){
			$this->CreateYST();
		}

		//未签署合同
		$orcontactModel = new OrderContract();
		$nosignNumber = $orcontactModel->where(['user_id'=>$this->userId,'sign'=>0])->count();
		$this->assign('nosignNumber',$nosignNumber);
		//未读消息
		$noticeModel = new Notice();
		$noticeNumber = $noticeModel->where(['uid'=>$this->userId,'isread'=>0])->count();
		$this->assign('noticeNumber',$noticeNumber);
    }
    //个人中心
    public function index()
    {	
		$PutModel = new Putlog();
		$where = ['uid'=>$this->userId];
		if(input('type')){
			$where['type'] = ['eq',input('type')];
		}
		if(input('start')){
			$where['create_time'][] = ['>=',strtotime(input('start').' 00:00')];
		}
		if(input('end')){
			$where['create_time'][] = ['<=',strtotime(input('end').' 23:59')];
		}
		$dataList = $PutModel->where($where)->order("id DESC")->paginate(8,false,['query'=>request()->param()]);
		$this->assign('dataList',$dataList);

		$this->assign('url',input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME'));
		// if($this->userId == 8844){
			// $yunClass = new Yunst();
			// //$res = $yunClass->backOrderTo('hry18583932273',['order'=>time().'hry','money'=>5]);
			// // $res = $yunClass->orderStatus('hry18583932273','NOjlFWUw2fZiQt1538287098');
			// $res = $yunClass->getCheckFile();
			// print_r($res);exit;
		// }
		return $this->fetch();
    }
	//好友
	public function invite(){
	
		$where['parentId'] = $this->userId;
		
		if(input('keywords')){
			$where['username'] = ['Like','%'.input('keywords').'%'];
		}
		$dataList = $this->cModel->where($where)->order('id DESC')->paginate(6,false,['query'=>request()->param()]);
		$this->assign('dataList',$dataList);
		return $this->fetch();
	}
	
	//项目管理
    public function project() {
        $OrModel = new Order();
        $where = ['a.uid' => $this->userId];
        $where['a.status'] = ['neq', 0];
        $where['a.delete_time'] = ['EXP', 'IS NULL'];
        if (input('keywords')) {
            $where['b.project_name'] = ['Like', '%' . input('keywords') . '%'];
        }
        $where['b.status'] = ['neq', 1];
        if (input('status')) {
            $where['b.status'] = ['eq', 6];
        } else {
            $where['b.status'] = ['neq', 6];
        }
//        $where['p.id'] = ['<',53];
        $where['a.type'] = ['neq',3];
        $where['b.id'] = ['neq',10];
        $dataList = $OrModel
                ->alias('a')
                ->field('a.*,b.project_name')
                ->join('tf_project b', 'a.project_id=b.id', 'LEFT')
                ->where($where)
                ->order("a.create_time DESC")
                ->paginate(6, false, ['query' => request()->param()]);
        $dataList->Project;
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    //项目明细
	public function projectinfo($id){
		$OrModel = new Order();
		$proModel = new Project();
		$where = ['uid'=>$this->userId];
		$where = ['project_id'=>$id];
		$dataList = $OrModel->where($where)->order('create_time desc')->select();
		$project = $proModel->where(['id'=>$id])->find();
		$total = $OrModel->where($where)->order('create_time desc')->sum('money');
		
		$this->assign('total',$total);
		$this->assign('dataList',$dataList);
		$this->assign('project',$project);
		return $this->fetch();
	}
	//账户管理
	public function info(){
		$lookintoModel = new Lookinto();
		$lookInfo = $lookintoModel->where(['uid'=>$this->userId])->order('create_time desc')->limit(1)->find();
		$this->assign('lookinfo',$lookInfo);
		return $this->fetch();
	}
	//合同管理
	public function contract(){
		$CotModel = new OrderContract();
		$where = ['a.user_id'=>$this->userId];
		$where['a.sign']  = 3;
		if(input('title')){
			$where['a.title|b.title']  = ['LIKE','%'.input('title').'%'];
		}
        $where['a.status']  = 1;
		$dataList = $CotModel->alias('a')->field('a.*')->join('tf_contract b','a.project_id=b.project_id','LEFT')->where($where)->order("id DESC")->paginate(6,false,['query'=>request()->param()]);
		$this->assign('dataList',$dataList);
		return $this->fetch();
	}
	//消息管理
	public function notice(){
		$NoModel = new Notice();
		if(request()->isAjax()){
			$id = input('post.id');
			$noticeInfo = $NoModel->where(['id'=>$id])->find();
			if($noticeInfo['isread'] !=1){
				$NoModel->where(['id'=>$id])->update(['isread'=>1]);
			}
			return ajaxReturn($noticeInfo['content'],1);
		}		
		$where = ['uid'=>$this->userId];
		$dataList = $NoModel->where($where)->order("create_time DESC")->paginate(6,false,['query'=>request()->param()]);
		$this->assign('dataList',$dataList);
		return $this->fetch();
	}
	//安全中心
	public function safe(){
		return $this->fetch();
	}
	//银行卡
	public function card(){
		$data = $this->cModel->where(['id'=>$this->userId])->find();		
		$CardModel = new Card();
		
		$dataList = $CardModel->where(['user_id'=>$this->userId,'status'=>1,'cardType'=>['neq',2]])->order("id DESC")->select();
		
		$this->assign('data', $data);
		$this->assign('dataList', $dataList);
		return $this->fetch();
	}
	//充值
	public function recharge(){
		$CardModel = new Card();
		$bankModel = new Bankcode();
		$CardList = $CardModel->where(['user_id'=>$this->userId,'status'=>1,'cardType'=>['neq',2]])->select();
		$bankList = $bankModel->select();
		$this->assign('CardList',$CardList);
		$this->assign('bankList',$bankList);
		return $this->fetch();
	}
	//提现
	public function getcash(){
		$CardModel = new Card();
		
		// $bizUserId = $this->cModel->where(['id'=>$this->userId])->value('bizUserId');
		// if($bizUserId){
			// $YunClass = new Yunst();
			// $res = $YunClass->Balance($bizUserId);
			// if($res['status'] == 'OK'){
				// $signedValue = json_decode($res['signedValue'],true);
				// //print_r($signedValue);
				// $money = $signedValue['allAmount'] / 100 ;
				// $this->cModel->where(['id'=>$this->userId])->update(['money'=>$money]);
			// }
		// }
		
		$CardList = $CardModel->where(['user_id'=>$this->userId,'status'=>1,'cardType'=>1])->select();
		$this->assign('CardList',$CardList);
		return $this->fetch();
	}	
	
	public function headimg(){
		
		$file = request()->file('photo');
		// 移动到框架应用根目录/public/uploads/ 目录下
		$newFilePath = "";
		if($file){
			$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS .'headimg');
			if($info){
				$newFilePath = '/uploads/headimg/' . str_replace('\\', '/', $info->getSaveName());
			}
		}
		$this->cModel->where(['id'=>$this->userId])->update(['head_thumb'=>$newFilePath]);
		$this->redirect('Member/info');
	}
    //实名认证
    public function authentication(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $data = input('post.');
            $certificate=$data['certificate'];
            $re=$this->cModel->where(['certificate'=>$certificate,'is_check'=>1])->value('id');
            if($re>1){
                return ajaxReturn('用户个人信息已经在其他账户下实名');
            }
            if($data['mobile_code'] != session('mobilecode')){
                $content = date('Y-m-d H:i:s').':用户手机号'.$data['bank_mobile'].'手机验证码不正确。';
                file_put_contents(date("Y-m-d H").'sendCode.txt',$content.PHP_EOL,FILE_APPEND);
                return ajaxReturn('手机验证码不正确');
            }
            $content = date('Y-m-d H:i:s').':用户手机号'.$data['bank_mobile'].'短信验证成功。'.json_encode($data);
            file_put_contents(date("Y-m-d H").'sendCode.txt',$content.PHP_EOL,FILE_APPEND);
            $mobile=$this->cModel->where(['id'=>$this->userId])->value('mobile');
            $bizUserId = 'hry'.$mobile;
            $YunClass->createMember($bizUserId);  //云商通创建会员 by hey
            $rut=$this->smrz($data);  // 云商通个人实名认证 by hey
            if($rut['status']=='OK'){
                $code=$this->cModel->where(['id'=>$this->userId])->value('certificate');
                if(empty($code)){
                    $this->cModel->where(['id'=>$this->userId])->update(['username'=>trim($data['username']),'certificate'=>$data['certificate'],'bank_card'=>$data['bank_card']]);
                }
                $member = $this->cModel->where(['id'=>$this->userId])->find();
                $credential= ['identity'=>$member['certificate']];
                $contents = date('Y-m-d H:i:s').':用户申请身份证验证，姓名'.$member['username'].',手机号'.$member['mobile'].'身份证'.$certificate.'。';
                file_put_contents(date("Y-m-d H").'auth.txt',$contents.PHP_EOL,FILE_APPEND);
                $this->ToBsetSign($member['username'],$member['mobile'],$credential);   //上上签用户注册  by hey
                $res = $this->cModel->where(['id'=>$this->userId])->update(['is_check'=>'1','ssqmobile'=>$mobile]);
                if($res){
                    $data['sex'] = get_sex($data['certificate']);
                    $data['ask'] = get_age($data['certificate']);
                    unset($data['mobile_code']);
                    $res1 = $this->cModel->where(['id'=>$this->userId])->update(array('sex'=>$data['sex'],'ask'=>$data['ask']));
                    if(!$res1){
                        $error['uid'] = $this->userId;
                        $error['sex'] = $data['sex'];
                        $error['ask'] = $data['ask'];
                        $error['error'] = '实名认证更新性别与年龄出错';
                        file_put_contents(date("Y-m-d H:i").'sex_auth.txt',json_encode($error,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                    }
                    $member = $this->cModel->where(['id'=>$this->userId])->find();
                    session('userName',$member['username']);
                    session('isCheck',1);
                }
                return ajaxReturn("认证成功",url('Member/info'));
            }else{
                return ajaxReturn($rut['message']);
            }
        }
        $is_check = $this->cModel->where(['id'=>$this->userId])->value('is_check');
        $member = $this->cModel->where(['id'=>$this->userId])->find()->toArray();
        $this->assign('member',$member);
        
        if($is_check){
            $this->redirect('Member/index');
        }
        return $this->fetch();
    }
    //实名认证
    private function smrz($data){
        $YunClass = new Yunst();
        $mobile=$this->cModel->where(['id'=>$this->userId])->value('mobile');
        $bizUserId = 'hry'.trim($mobile);
        $username=trim($data['username']);
        $certificate=trim($data['certificate']);
        /*$bizUserId = 'hry19934575138';
        $username='杜凤';
        $certificate='510922199001087063';*/
        $rut=$YunClass->setRealName($bizUserId,$username,$certificate);
        return $rut;
    }
    //发送短信
    public function sendcode(){
        if(request()->isAjax()){
            $Mobilelog=new Mobilelog();
            $mobile = input('post.mobile');
            $old=$Mobilelog->where(['oldmobile'=>$mobile])->find();
            if(!empty($old)){
                return ajaxReturn('该手机号已被系统注销.');
            }
            if(!captcha_check(input('post.code'))){
                return ajaxReturn('图形验证码不正确');
            }
            $code = rand(1000,9999);
            $res = SmsSend($mobile,$code);
            if($res['code'] == 0){
                session('mobilecode',$code);
                $content = date('Y-m-d H:i:s').':用户手机号'.$mobile.'短信验证码发送成功。';
                file_put_contents(date("Y-m-d H").'sendCode.txt',$content.PHP_EOL,FILE_APPEND);
                return ajaxReturn('发送成功',url('Member/info'));
            }else{
                return ajaxReturn($res['detail']);
            }
        }
    }

    //发送修改登录手机验证码短信
    public function sendcode1(){
        if(request()->isAjax()){
            //$Mobilelog=new Mobilelog();
            $mobile = input('post.mobile');
            /*$old=$Mobilelog->where(['oldmobile'=>$mobile])->find();
            if(!empty($old)){
                return ajaxReturn('该手机号已被系统注销.');
            }*/
            $code = rand(1000,9999);
            $res = SmsSend($mobile,$code);
            if($res['code'] == 0){
                session('mobilecode',$code);
                session('mobile',$mobile);
                return ajaxReturn('发送成功',url('Member/info'));
            }else{
                return ajaxReturn($res['detail']);
            }
        }
    }
    //更改账号第一步
    public function updatemobile(){
        ajaxReturn('修改登录手机号功能已关闭，请联系客服!');
        if(request()->isAjax()){
            $Mobilelog=new Mobilelog();
            $code = input('post.code');
            $strlen=mb_strlen($code,'UTF8');
            $mobile=session('mobile');
            if($strlen!=4){
                return ajaxReturn('手机验证码不正确','',2);
            }
            if($code != session('mobilecode')){
                return ajaxReturn('手机验证码不正确','',2);
            }
            $old=$Mobilelog->where(['oldmobile'=>$mobile])->find();
            if(!empty($old)){
                return ajaxReturn('该手机号已被系统注销.');
            }
            return ajaxReturn('验证成功');
        }
    }

    //更改账号第二步
    public function updatemember(){
        ajaxReturn('修改登录手机号功能已关闭，请联系客服!');
        if(request()->isAjax()){
            $Mobilelog=new Mobilelog();
            $code=input('post.code');
            $strlen=mb_strlen($code,'UTF8');
            if($strlen!=4){
                return ajaxReturn('手机验证码不正确');
            }
            $newmobile=input('post.mobile');
            if($code != session('mobilecode')){
                return ajaxReturn('手机验证码不正确');
            }
            if($newmobile != session('mobile')){
                return ajaxReturn('绑定手机与收取验证码手机不一致!');
            }
            $id=$this->userId;
            $oldmobie=$this->cModel->where(['id'=>$id])->value('mobile');
            $data = [
                'oldmobile' => $oldmobie,
                'newmobile' => $newmobile,
                'uid' => $id,
                'time' => date('Y-m-d H:i:s')
            ];
            $old=$Mobilelog->where(['oldmobile'=>$newmobile])->find();
            if(!empty($old)){
                return ajaxReturn('该手机号已被系统注销,无法再次作为登录账号');
            }
            $memold=$this->cModel->where(['mobile'=>$newmobile])->find();
            if(!empty($memold)){
                return ajaxReturn('该手机号已存在');
            }
            $res=$Mobilelog->insert($data);
            if($res){
                $rut=$this->cModel->where(['id'=>$id])->update(['mobile'=>$newmobile]);
                if($rut){
                    return ajaxReturn('修改成功',url('member/safe'));
                }
                return ajaxReturn('修改失败');
            }
        }
    }
    //忘记账号
    public function findmobile(){
        if(request()->isAjax()){
            $Mobilelog=new Mobilelog();
            $code=input('post.code');
            if($code != session('mobilecode')){
                return ajaxReturn('手机验证码不正确');
            }
            $strlen=mb_strlen($code,'UTF8');
            if($strlen!=4){
                return ajaxReturn('手机验证码不正确');
            }
            $mobile=input('post.mobile');
            $idcard=input('post.idcard');
            $name=input('post.username');
            $id=$this->userId;
            $userdata=$this->cModel->where(['id'=>$id])->find()->toArray();

            if($userdata['username']!=$name){
                return ajaxReturn('你输入的身份信息非本人信息,请核实.');
            }elseif ($userdata['certificate']!=$idcard){
                return ajaxReturn('你输入的身份信息非本人信息,请核实.');
            }
            $data = [
                'oldmobile' => $userdata['mobile'],
                'newmobile' => $mobile,
                'uid' => $id,
                'time' => date('Y-m-d H:i:s')
            ];

            $memold=$this->cModel->where(['mobile'=>$mobile])->find();
            if(!empty($memold)){
                return ajaxReturn('该手机号已存在');
            }
            $old=$Mobilelog->where(['oldmobile'=>$mobile])->find();
            if(!empty($old)){
                return ajaxReturn('该手机号已被系统注销,无法再次作为登录账号');
            }
            $semobile=session('mobile');
            if($semobile!=$mobile){
                return ajaxReturn('该手机号与收验证码手机不一致');
            }
            $res=$Mobilelog->insert($data);
            if($res){
                $rut=$this->cModel->where(['id'=>$id])->update(['mobile'=>$mobile]);
                if($rut){
                    return ajaxReturn('修改成功',url('Member/safe'));
                }
                return ajaxReturn('修改失败');
            }
        }
    }


    //修改密码
	public function logpass(){
		if(request()->isAjax()){
			$data = input('post.');
			$where = ['id'=>$this->userId];
			$oldpass = $this->cModel->where($where)->value('password');
			if($oldpass != md5($data['oldpass']) && $oldpass != md5(md5($data['oldpass'])) && !password_verify($data['oldpass'],$oldpass)){
				return ajaxReturn('旧密码不正确');
			}
			if($oldpass == md5($data['newpass'])){
				return ajaxReturn('新密码与旧密码不能相同');
			}
			if(strlen($data['newpass']) > 20 || strlen($data['newpass']) < 6){
                return ajaxReturn('新密码应在6-20位之间');
            }
			$result = $this->cModel->where($where)->update(['password'=>md5($data['newpass'])]);
			if($result){
                session('UID',null);
                session('userName',null);
                session('mobile',null);
                session('member_token',null);
				return ajaxReturn('修改成功',url('Member/info'));
			}else{
				return ajaxReturn($this->cModel->getError());
			}
		}
	}
	//上上签 - 注册个人用户
	private function ToBsetSign($name,$mobile,$credential){
		$bestSign_demo = new BestSignDemo();
		$account = $mobile;
		$user_type = "1";
		$response = $bestSign_demo->regUser($account,$mobile, $name, $user_type, $credential,1);
		if($response->errno == 0){
                    $content = date('Y-m-d H:i:s').':用户手机号'.$mobile.'身份证检查通过,taskId:'.$response->data->taskId.'。';
                    file_put_contents(date("Y-m-d H").'auth.txt',$content.PHP_EOL,FILE_APPEND);
			$this->cModel->where(['id'=>$this->userId])->update(['task_id'=>$response->data->taskId,'ssqmobile'=>$mobile]);
			return $response->data->taskId;
		}else{
			return $response->errmsg;
		}
	}
	//云商通-创建会员/实名认证
	private function CreateYST(){
		$YunClass = new Yunst();
		$Minfo = $this->cModel->where(['id'=>$this->userId])->find();
		$bizUserId = 'hry'.$Minfo['mobile'];
		$res = $YunClass->createMember($bizUserId);
		if($res['status'] == 'OK'){
			$signedValue = json_decode($res['signedValue'],true);
			$this->cModel->where(['id'=>$this->userId])->update(['YstId'=>$signedValue['userId'],'bizUserId'=>$signedValue['bizUserId']]);
			return $YunClass->setRealName($bizUserId,$Minfo['username'],$Minfo['certificate']);
		}elseif($res['message'] == '所属应用下已经存在此用户'){
			$this->cModel->where(['id'=>$this->userId])->update(['bizUserId'=>$bizUserId]);

            $YunClass->setRealName($bizUserId,$Minfo['username'],$Minfo['certificate']);
		}
	}

    //云商通-创建会员/实名认证
    private function CreateRealName(){
        $YunClass = new Yunst();
        $Minfo = $this->cModel->where(['id'=>$this->userId])->find();
        $bizUserId = 'hry'.$Minfo['mobile'];
        $res=$YunClass->setRealName($bizUserId,$Minfo['username'],$Minfo['certificate']);
        //echo '<pre/>';print_r($res);exit;
        return $res;
    }

	//问卷调查
	public function lookinto(){
		$InvestModel = new Invest();
		$QuestModel = new Question();
		$title = $InvestModel->where(['id'=>3,'is_disable'=>1])->value('title');

		$dataList = $QuestModel->where(['jid'=>3,'is_check'=>1])->order('id ASC')->select();
		
		foreach($dataList as &$v){
			$v['answer'] = Db::table('tf_answer')->where(['qid'=>$v['id'],'is_check'=>1])->order('id ASC')->select();
		}
		unset($v);
		$this->assign('title',$title);
		$this->assign('dataList',$dataList);
		$this->assign('totalAll',count($dataList));
		return $this->fetch();
	}
	
	//评估
	public function assess(){
		if(request()->isAjax()){
			$lookintoModel = new Lookinto();
			$data = input('post.');
			$score = 0;
			foreach($data as $k=>$v){
				$score += $v;
			}
			$LookName = $this->getLookName($score);
			$insertData = [
				'uid' => $this->userId,
				'aid' => 3,
				'content' => serialize($data),
				'score' => $score,
				'create_time' => time(),
				'name'	=> $LookName
				];
			$res = $lookintoModel->insert($insertData);
			if($res){
				return ajaxReturn('恭喜!您是一位'.$LookName.'的投资人',url('Member/info'));
			}else{
				return ajaxReturn($lookintoModel->getError());
			}			
		}
	}
	//平台公告
	public function affiche(){
		$artModel = new Archive();
		
		$where['typeid'] = 2;
		$where['status'] = 1;
		$where['mod'] = 'addonarticle';
		$order = 'create_time desc';
		$dataList = $artModel->where($where)->order($order)->paginate(6,false,['query'=>request()->param()]);
		$this->assign('dataList', $dataList);
		return $this->fetch();
	}
	
	private function getLookName($score){
		$name = Db::table('tf_rank')->where(['points'=>['>=',$score]])->order('points asc')->limit(1)->value('rankname');
//		echo Db::table('tf_rank')->getLastSql();
		return $name;
	}

    public function service(){
        return $this->fetch('service');
    }

    public function serviceType(){
        return $this->fetch('servicetype');
    }


}
